from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.models.user import User
from app.schemas.permission import Permission as PermissionSchema, PermissionCreate, PermissionUpdate, PermissionList, PermissionByCategory
from app.services.permission_service import PermissionService
from app.api.deps import get_current_active_user, get_current_superuser
from app.api.dependencies import get_permission_service

router = APIRouter(prefix="/permissions", tags=["permissions"])


@router.get("/", response_model=PermissionList)
async def get_permissions(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(100, ge=1, le=1000, description="返回的记录数"),
    is_active: Optional[bool] = Query(None, description="是否激活"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    category: Optional[str] = Query(None, description="权限分类"),
    permission_service: PermissionService = Depends(get_permission_service),
    current_user: User = Depends(get_current_active_user)
):
    """获取权限列表"""
    
    if category:
        permissions = permission_service.get_by_category(category)
        total = len(permissions)
        permissions = permissions[skip:skip + limit]
    elif search:
        permissions = permission_service.search_permissions(search, skip, limit)
        total = len(permissions)
    else:
        permissions = permission_service.get_all(skip, limit, is_active)
        total = len(permissions)
    
    return PermissionList(
        items=permissions,
        total=total,
        page=skip // limit + 1,
        size=limit
    )


@router.get("/{permission_id}", response_model=PermissionSchema)
async def get_permission(
    permission_id: int,
    permission_service: PermissionService = Depends(get_permission_service),
    current_user: User = Depends(get_current_active_user)
):
    """获取指定权限信息"""
    permission = permission_service.get_by_id(permission_id)
    
    if not permission:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="权限不存在"
        )
    
    return permission


@router.post("/", response_model=PermissionSchema)
async def create_permission(
    permission_data: PermissionCreate,
    permission_service: PermissionService = Depends(get_permission_service),
    current_user: User = Depends(get_current_superuser)
):
    """创建新权限（需要超级用户权限）"""
    try:
        permission = permission_service.create_permission(permission_data)
        return permission
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="权限创建失败"
        )


@router.put("/{permission_id}", response_model=PermissionSchema)
async def update_permission(
    permission_id: int,
    permission_data: PermissionUpdate,
    permission_service: PermissionService = Depends(get_permission_service),
    current_user: User = Depends(get_current_superuser)
):
    """更新权限信息（需要超级用户权限）"""
    try:
        permission = permission_service.update_permission(permission_id, permission_data)
        return permission
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="权限更新失败"
        )


@router.delete("/{permission_id}")
async def delete_permission(
    permission_id: int,
    permission_service: PermissionService = Depends(get_permission_service),
    current_user: User = Depends(get_current_superuser)
):
    """删除权限（需要超级用户权限）"""
    
    try:
        success = permission_service.delete_permission(permission_id)
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="权限不存在"
            )
        
        return {"message": "权限删除成功"}
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="权限删除失败"
        )


@router.get("/categories/list")
async def get_categories(
    permission_service: PermissionService = Depends(get_permission_service),
    current_user: User = Depends(get_current_active_user)
):
    """获取所有权限分类"""
    categories = permission_service.get_categories()
    return {"categories": categories}


@router.get("/grouped/category", response_model=List[PermissionByCategory])
async def get_grouped_permissions(
    permission_service: PermissionService = Depends(get_permission_service),
    current_user: User = Depends(get_current_active_user)
):
    """按分类分组获取权限"""
    grouped_permissions = permission_service.get_grouped_by_category()
    return grouped_permissions


@router.get("/tree/structure")
async def get_permission_tree(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取权限树形结构"""
    permission_service = PermissionService(db)
    tree = permission_service.get_permission_tree()
    return tree


@router.post("/system/init")
async def init_system_permissions(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_superuser)
):
    """初始化系统权限（需要超级用户权限）"""
    permission_service = PermissionService(db)
    try:
        permissions = permission_service.create_system_permissions()
        return {
            "message": "系统权限初始化成功",
            "created_count": len(permissions),
            "permissions": [perm.to_dict() for perm in permissions]
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="系统权限初始化失败"
        )